package com.sike.netty.jinjie.codec.protocol;

import com.alibaba.fastjson.JSONObject;
import com.sike.netty.jinjie.codec.protocol.decoder.ByteToStringDecoder;
import com.sike.netty.jinjie.codec.protocol.decoder.StringToObjectDecoder;
import com.sike.netty.jinjie.codec.protocol.message.ChatMessage;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class Server {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup(),new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,5,4,0,0));
                        ch.pipeline().addLast(new ByteToStringDecoder());
                        ch.pipeline().addLast(new StringToObjectDecoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                             @Override
                             public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                 ChatMessage chatMessage = (ChatMessage) msg;
                                System.out.println("接受内容:" + chatMessage.getContent());
                            }
                        });
                    }
                }).bind(8081);
    }
}
